<?php

declare (strict_types = 1);

namespace auth;

use support\Str;
use think\model\relation\MorphMany;

trait HasApiToken
{
    /**
     * Token 实例关联
     *
     * @return \think\model\relation\MorphMany
     */
    public function tokens(): MorphMany
    {
        return $this->morphMany(AccessToken::class, 'tokenable');
    }

    /**
     * 生成 token
     *
     * @return \auth\NewAccessToken
     * @throws \Exception
     */
    public function generateToken(): NewAccessToken
    {
        $newToken = hash('sha256', $plainTextToken = Str::random(40));
        if (config('auth.single_endpoint', true)
            && $this->tokens()->count()) {
            $this->tokens()->update([
                'token'       => $newToken,
                'update_time' => date('Y-m-d H:i:s'), // 这里的 update 方法不是模型方法，自动时间戳无效，具体参见 \db\Query
            ]);
            $token = $this->tokens()->find();
        } else {
            $token = $this->tokens()->save([
                'token' => $newToken,
            ]);
        }

        return new NewAccessToken($token, $plainTextToken);
    }
}
